#include "tmsessionmanager.h"
#include "tmglobaldef.h"

void ClientSessionManagerI::remove_session(ClientSessionI *pSession)
{
    IceUtil::Mutex::Lock lock(m_MapMutex);

    std::map<ClientSessionI*, std::string>::iterator it;
    it = m_mapSession.find(pSession);
    if( it!=m_mapSession.end() ){
        QString m_name = stdToQString(m_mapSession.at(pSession));
        if(m_name.contains("user")){
            pMySqlCtrl->saveUserState(m_name.right(m_name.size()-5),TMMySQLCtrl::OFFLINE);
        }else{
            robotMap.remove(m_name);
            pMySqlCtrl->updateRobotState(m_name,TMMySQLCtrl::OFFLINE);
            g_pLog->log_D(QString("robotMap size: %1").arg(robotMap.size()));
        }
        m_mapSession.erase(pSession);
    }
}

void ClientSessionManagerI::list_session(Ice::StringSeq &strList)
{
    IceUtil::Mutex::Lock lock(m_MapMutex);

    std::map<ClientSessionI*, std::string>::iterator it;
    for(it=m_mapSession.begin();it!=m_mapSession.end();it++)
    {
//        qDebug()<<"ClientSessionManagerI::list_session"<<it->second.c_str();
        strList.push_back(it->second);
    }
}

Glacier2::SessionPrx ClientSessionManagerI::create(const std::string &userId, const Glacier2::SessionControlPrx &sPrx, const Ice::Current &current)
{

    IceUtil::Mutex::Lock lock(m_MapMutex);

    g_pLog->log_D("创建session成功");
    Ice::Identity ident = { IceUtil::generateUUID(), "session" };
    ClientSessionI* pClientSession = new ClientSessionI(this);
    m_mapSession.insert(std::make_pair(pClientSession, userId));
    return Glacier2::SessionPrx::uncheckedCast(current.adapter->add(pClientSession, ident));
}

ClientSessionI::ClientSessionI(const ClientSessionManagerI *pMgr)
{
    m_sessionMgr = (ClientSessionManagerI*)pMgr;
    qDebug()<<"[ClientSessionI]: create";
}

void ClientSessionI::ice_ping(const Ice::Current &cur) const
{
    qDebug()<<"[ClientSessionI]: ice_ping";
    g_pLog->log_D("[ClientSessionI]: ice_ping ");
}

void ClientSessionI::destroy(const Ice::Current &cur)
{
    m_sessionMgr->remove_session(this);
    qDebug()<<"[ClientSessionI]: destroy";
}

bool DummyPermissionsVerifierI::checkPermissions(const std::string &userId, const std::string &password, std::string &, const Ice::Current &) const
{
    QString userName = stdToQString(userId);
    QString userPwd = stdToQString(password);
    if(userName.contains("user")){
        if(userPwd == pMySqlCtrl->queryPwdByName(userName.right(userName.size()-5))){
            pMySqlCtrl->saveUserState(userName.right(userName.size()-5),TMMySQLCtrl::ONLINE);
            g_pLog->log_D("用户登陆校验成功 ");
            return true;
        }
        g_pLog->log_D("用户登陆校验失败 ");
        return false;
    }
    g_pLog->log_D("机器人登陆校验成功 ");
    return true;
}
